package com.pubsub;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class EmitLog {

    /**
     * 实际上，消息只能发送给交换机而不是队列，由交换机把消息转发给去队列存储
     *
     * 发布订阅：fanout类型交换机，主要是引入交换机概念，讲解
     */
  private static final String EXCHANGE_NAME = "logs";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    try (Connection connection = factory.newConnection();
         Channel channel = connection.createChannel()) {
        // 交换机的类型有：fanout，topic，direct，headers见BuiltinExchangeType
        //空（“”）名字的交换机就是默认交换机或者叫无名字（nameless）的交换机

        //fanout类型的交换机会把消息分发给与其绑定的所有队列，相当于广播
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        String message = argv.length < 1 ? "info: Hello World!" :
                            String.join(" ", argv);

        // 如果没指定交换机名字的话，消息会发送给名字为指定的routingKey（第二个参数）的队列
        // 由于交换机是fanout,会把消息发给绑定的所有队列，所以routingKey的值是会被忽略的，这里干脆就写一个空字符串
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes("UTF-8"));
        System.out.println(" [x] Sent '" + message + "'");
    }
  }
}